import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    private DatagramSocket client;

    public static void main(String[] args){
        UDPClient client = new UDPClient();
        //建立死循环，不断发送数据
        for(int i=0;i<10;i++){
        	try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            //打印响应的数据
            System.out.println(client.sendAndReceive("127.0.0.1",8081,"m"+i+""));
        }
    }

    private String sendAndReceive(String ip, int port, String msg) {
        String responseMsg = "";

        try {
            //创建客户端的DatagramSocket对象，不必传入地址和对象
            client = new DatagramSocket();
            byte[] sendBytes = msg.getBytes();
            //封装要发送目标的地址
            InetAddress address = InetAddress.getByName(ip);
            //封装要发送的DatagramPacket的对象，由于要发送到目的主机，所以要加上地址和端口号
            DatagramPacket sendPacket = new DatagramPacket(sendBytes,sendBytes.length,address,port);

            try {
            	
                //发送数据
                client.send(sendPacket);
            }catch (Exception e){
                e.printStackTrace();
            }

            byte[] responseBytes = new byte[2048];
            //创建响应信息的DatagramPacket对象
            DatagramPacket responsePacket = new DatagramPacket(responseBytes,responseBytes.length);
            client.receive(responsePacket);
            
            //解析数据包内容
            if(responsePacket.getLength() < 0){
            	responseMsg = "no data";
            }else{
            	responseMsg = new String(responsePacket.getData(),0,responsePacket.getLength());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭客户端
            if(client != null){
                client.close();
                client = null;
            }
        }

        return responseMsg;
    }
}